// pages/order-detail/order-detail.js
const api = require('../../utils/api')
const { PaymentService } = require('../../utils/payment')
const { safeGet, completeOrder, validateOrder } = require('../../utils/data-validator')
const app = getApp()
const request = require('../../utils/request')
const payment = require('../../utils/payment')
const dateUtil = require('../../utils/date')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: null,
    order: {},
    showActionBar: true,
    needPay: false,
    
    // 取消订单
    showCancelModal: false,
    selectedReason: '',
    cancelReasons: [
      '不想要了',
      '商品信息填错了',
      '地址填写错误',
      '优惠券使用错误',
      '其他原因'
    ],
    
    // 状态更新
    trackingTimer: null,
    lastUpdateTime: null,
    statusMap: {
      PENDING_PAYMENT: { text: '待付款', color: '#ff9800', desc: '请尽快完成支付' },
      PAID: { text: '已付款', color: '#2196f3', desc: '商家正在接单中' },
      PROCESSING: { text: '处理中', color: '#2196f3', desc: '商家正在准备商品' },
      DELIVERING: { text: '配送中', color: '#00bcd4', desc: '骑手正在配送中' },
      COMPLETED: { text: '已完成', color: '#4caf50', desc: '订单已完成' },
      CANCELLED: { text: '已取消', color: '#9e9e9e', desc: '订单已取消' },
      REFUNDED: { text: '已退款', color: '#9e9e9e', desc: '订单已退款' }
    },
    loading: true,
    showCancelDialog: false,
    showRefundDialog: false,
    refundReasons: [
      '不想要了',
      '商品缺货',
      '店铺太忙',
      '送餐太慢',
      '其他原因'
    ],
    selectedRefundReason: '',
    showDeliveryInfo: false,
    deliveryInfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id, needPay } = options
    if (id) {
      this.setData({ 
        orderId: parseInt(id),
        needPay: needPay === 'true'
      })
      this.loadOrderDetail()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 刷新订单详情
    if (this.data.orderId) {
      this.loadOrderDetail()
      this.startOrderTracking()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.stopOrderTracking()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadOrderDetail()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 加载订单详情
  async loadOrderDetail(showLoading = true) {
    try {
      if (showLoading) {
        wx.showLoading({ title: '加载中...' })
      }
      
      let orderData
      
      try {
        // 尝试调用真实API
        const result = await api.getOrderDetail(this.data.orderId)
        if (result.code === 200) {
          orderData = result.data
          console.log('订单详情加载成功:', orderData)
        } else {
          throw new Error(result.message || '获取订单详情失败')
        }
      } catch (apiError) {
        console.log('API调用失败，使用本地数据:', apiError.message)
        
        // 先尝试从本地存储的订单中查找
        const localOrders = wx.getStorageSync('mockOrders') || []
        const localOrder = localOrders.find(order => order.id == this.data.orderId)
        
        if (localOrder) {
          orderData = localOrder
          console.log('从本地存储加载订单:', orderData)
        } else {
          // 如果本地也没有，使用模拟数据
          orderData = this.generateMockOrder()
          console.log('使用模拟订单数据:', orderData)
        }
      }
      
      // 验证和补全订单数据
      const validation = validateOrder(orderData)
      if (validation.warnings.length > 0) {
        console.warn('订单数据警告:', validation.warnings)
      }
      
      const completeOrderData = completeOrder(orderData)
      
      this.setData({ 
        order: completeOrderData,
        showActionBar: this.shouldShowActionBar(completeOrderData.status),
        lastUpdateTime: new Date()
      })
      
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: `订单详情 - ${orderData.orderNo || orderData.id}`
      })
      
      // 如果需要支付，自动弹出支付
      if (this.data.needPay && orderData.status === 'PENDING_PAYMENT') {
        this.setData({ needPay: false })
        setTimeout(() => {
          this.payOrder()
        }, 1000)
      }
      
      if (showLoading) {
        wx.hideLoading()
      }
      
    } catch (error) {
      console.error('加载订单详情失败:', error)
      if (showLoading) {
        wx.hideLoading()
      }
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 开始订单状态跟踪
  startOrderTracking() {
    this.stopOrderTracking() // 先停止之前的定时器
    
    const order = this.data.order
    if (!order || !order.status) return
    
    // 只有特定状态需要跟踪
    const trackingStatuses = ['PENDING_PAYMENT', 'PAID', 'PREPARING', 'DELIVERING']
    if (!trackingStatuses.includes(order.status)) {
      return
    }
    
    console.log('开始订单状态跟踪:', order.id)
    
    this.data.trackingTimer = setInterval(() => {
      this.updateOrderStatus()
    }, 30000) // 每30秒更新一次
  },

  // 停止订单状态跟踪
  stopOrderTracking() {
    if (this.data.trackingTimer) {
      clearInterval(this.data.trackingTimer)
      this.setData({ trackingTimer: null })
      console.log('停止订单状态跟踪')
    }
  },

  // 更新订单状态
  async updateOrderStatus() {
    try {
      const orderId = this.data.orderId
      if (!orderId) return
      
      console.log('更新订单状态:', orderId)
      
      // 调用API获取最新状态
      const result = await api.getOrderDetail(orderId)
      
      if (result.code === 200) {
        const newOrder = result.data
        const oldStatus = this.data.order.status
        const newStatus = newOrder.status
        
        // 更新订单数据
        this.setData({ 
          order: newOrder,
          showActionBar: this.shouldShowActionBar(newStatus),
          lastUpdateTime: new Date()
        })
        
        // 如果状态发生变化，显示通知
        if (oldStatus !== newStatus) {
          this.onOrderStatusChanged(oldStatus, newStatus, newOrder)
        }
        
        // 如果订单完成或取消，停止跟踪
        if (['COMPLETED', 'CANCELLED'].includes(newStatus)) {
          this.stopOrderTracking()
        }
        
      } else {
        console.error('获取订单状态失败:', result.message)
      }
      
    } catch (error) {
      console.error('更新订单状态失败:', error)
      // 网络错误等不影响继续跟踪
    }
  },

  // 订单状态变化处理
  onOrderStatusChanged(oldStatus, newStatus, order) {
    console.log('订单状态变化:', { oldStatus, newStatus, orderId: order.id })
    
    // 状态变化提示
    const statusMessages = {
      'PAID': '订单支付成功，商家正在准备中',
      'PREPARING': '商家已接单，正在制作中',
      'DELIVERING': '订单已出餐，正在配送中',
      'COMPLETED': '订单已完成，感谢您的使用',
      'CANCELLED': '订单已取消'
    }
    
    const message = statusMessages[newStatus]
    if (message) {
      wx.showToast({
        title: message,
        icon: newStatus === 'COMPLETED' ? 'success' : 'none',
        duration: 3000
      })
    }
    
    // 特殊状态处理
    if (newStatus === 'COMPLETED') {
      // 订单完成，可以引导用户评价
      setTimeout(() => {
        this.promptReview(order.id)
      }, 3000)
    }
  },

  // 提示用户评价
  promptReview(orderId) {
    wx.showModal({
      title: '订单已完成',
      content: '您的订单已送达，快来评价一下吧！',
      confirmText: '去评价',
      cancelText: '稍后评价',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/review/review?orderId=${orderId}`
          })
        }
      }
    })
  },

  // 生成模拟订单数据
  generateMockOrder() {
    const now = new Date()
    const orderId = this.data.orderId
    
    // 根据订单ID生成不同状态的订单
    const orders = {
      1: {
        id: 1,
        orderNo: 'ORD20240101001',
        status: 'DELIVERING',
        type: 'DELIVERY',
        totalAmount: '46.00',
        productAmount: '36.50',
        deliveryFee: '3.00',
        packagingFee: '2.00',
        discountAmount: '5.50',
        createdAt: new Date(now.getTime() - 2 * 60 * 60 * 1000),
        paymentTime: new Date(now.getTime() - 1.5 * 60 * 60 * 1000),
        estimatedDeliveryTime: new Date(now.getTime() + 15 * 60 * 1000),
        deliveryAddress: '北京市朝阳区三里屯路19号院',
        receiverName: '张三',
        receiverPhone: '138****8888',
        deliveryNote: '不要辣椒，多放香菜',
        store: {
          id: 1,
          name: '麦当劳(王府井店)',
          avatarUrl: '/images/stores/mcdonalds.jpg',
          address: '北京市东城区王府井大街138号',
          phone: '010-12345678',
          businessHours: '08:00-22:00',
          rating: 4.5
        },
        items: [
          {
            productId: 1,
            name: '巨无霸',
            image: '/images/products/bigmac.jpg',
            price: 24.5,
            quantity: 1,
            specifications: '标准'
          },
          {
            productId: 3,
            name: '薯条(大)',
            image: '/images/products/fries.jpg',
            price: 12.0,
            quantity: 1,
            specifications: '大份'
          }
        ]
      },
      2: {
        id: 2,
        orderNo: 'ORD20240101002',
        status: 'COMPLETED',
        type: 'DELIVERY',
        totalAmount: '57.50',
        productAmount: '52.00',
        deliveryFee: '3.00',
        packagingFee: '2.50',
        createdAt: new Date(now.getTime() - 24 * 60 * 60 * 1000),
        paymentTime: new Date(now.getTime() - 23.5 * 60 * 60 * 1000),
        completedAt: new Date(now.getTime() - 23 * 60 * 60 * 1000),
        deliveryAddress: '北京市海淀区中关村大街1号',
        receiverName: '李四',
        receiverPhone: '139****9999',
        store: {
          id: 2,
          name: '肯德基(三里屯店)',
          avatarUrl: '/images/stores/kfc.jpg',
          address: '北京市朝阳区三里屯路11号',
          phone: '010-87654321',
          businessHours: '09:00-23:00',
          rating: 4.3
        },
        items: [
          {
            productId: 5,
            name: '新奥尔良烤翅',
            image: '/images/products/spicy-chicken.jpg',
            price: 16.0,
            quantity: 2,
            specifications: '2只装'
          },
          {
            productId: 7,
            name: '香辣鸡腿堡',
            image: '/images/products/burger.jpg',
            price: 22.0,
            quantity: 1,
            specifications: '中辣'
          }
        ]
      },
      3: {
        id: 3,
        orderNo: 'ORD20240101003',
        status: 'PENDING_PAYMENT',
        type: 'DINE_IN',
        totalAmount: '128.00',
        productAmount: '128.00',
        createdAt: new Date(now.getTime() - 30 * 60 * 1000),
        store: {
          id: 3,
          name: '海底捞火锅(中关村店)',
          avatarUrl: '/images/stores/haidilao.jpg',
          address: '北京市海淀区中关村大街27号',
          phone: '010-11111111',
          businessHours: '10:00-02:00',
          rating: 4.8
        },
        items: [
          {
            productId: 8,
            name: '番茄锅底',
            image: '/images/products/hotpot.jpg',
            price: 38.0,
            quantity: 1,
            specifications: '不辣'
          },
          {
            productId: 10,
            name: '精品肥牛',
            image: '/images/products/soup.jpg',
            price: 58.0,
            quantity: 1,
            specifications: '200g'
          },
          {
            productId: 12,
            name: '手工面条',
            image: '/images/products/noodles.jpg',
            price: 32.0,
            quantity: 1,
            specifications: '细面'
          }
        ]
      }
    }
    
    return orders[orderId] || orders[1]
  },

  // 判断是否显示操作栏
  shouldShowActionBar(status) {
    return ['PENDING_PAYMENT', 'DELIVERING', 'COMPLETED', 'PAID', 'PREPARING'].includes(status)
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'PENDING_PAYMENT': '待支付',
      'PAID': '已支付',
      'PREPARING': '制作中',
      'READY': '待取餐',
      'DELIVERING': '配送中',
      'COMPLETED': '已完成',
      'CANCELLED': '已取消',
      'REFUNDED': '已退款'
    }
    return statusMap[status] || status
  },

  // 格式化时间
  formatTime(time) {
    if (!time) return ''
    
    const date = new Date(time)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    
    if (diff < 0) {
      // 未来时间，显示倒计时
      const minutes = Math.ceil(Math.abs(diff) / (60 * 1000))
      return `${minutes}分钟后`
    } else if (diff < 60 * 1000) {
      return '刚刚'
    } else if (diff < 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 1000))}分钟前`
    } else if (diff < 24 * 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
    } else {
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  },

  // 计算商品小计
  calculateProductAmount(items) {
    if (!items || items.length === 0) return '0.00'
    
    const total = items.reduce((sum, item) => {
      return sum + (item.price * item.quantity)
    }, 0)
    
    return total.toFixed(2)
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 跳转到店铺详情
  goToStore() {
    wx.navigateTo({
      url: `/pages/store-detail/store-detail?id=${this.data.order.store.id}&orderType=delivery`
    })
  },

  // 取消订单
  cancelOrder() {
    this.setData({
      showCancelModal: true,
      selectedReason: ''
    })
  },

  // 隐藏取消弹窗
  hideCancelModal() {
    this.setData({ showCancelModal: false })
  },

  // 选择取消原因
  selectCancelReason(e) {
    const reason = e.currentTarget.dataset.reason
    this.setData({ selectedReason: reason })
  },

  // 确认取消订单
  confirmCancel() {
    if (!this.data.selectedReason) return
    
    wx.showLoading({ title: '取消中...' })
    
    // 模拟取消订单
    setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '订单已取消',
        icon: 'success'
      })
      
      // 更新订单状态
      this.setData({
        'order.status': 'CANCELLED',
        showCancelModal: false,
        showActionBar: false
      })
    }, 1000)
  },

  // 支付订单
  async payOrder() {
    const order = this.data.order
    
    if (!order || order.status !== 'PENDING_PAYMENT') {
      wx.showToast({
        title: '订单状态异常',
        icon: 'none'
      })
      return
    }
    
    try {
      console.log('开始支付订单:', order.id)
      
      // 使用微信支付作为默认支付方式
      const paymentMethod = 'wechat'
      const amount = order.totalAmount
      
      const payment = new PaymentService()
      const paymentResult = await payment.pay(order.id, paymentMethod, amount)
      
      console.log('支付成功:', paymentResult)
      
      // 支付成功，更新订单状态
      this.setData({
        'order.status': 'PAID',
        'order.paymentTime': new Date(),
        showActionBar: this.shouldShowActionBar('PAID')
      })
      
      // 重新开始状态跟踪
      this.startOrderTracking()
      
      wx.showToast({
        title: '支付成功',
        icon: 'success'
      })
      
    } catch (error) {
      console.error('支付失败:', error)
      
      let message = '支付失败，请重试'
      
      if (error.errorCode === 'USER_CANCEL') {
        message = '您已取消支付'
      } else if (error.message) {
        message = error.message
      }
      
      wx.showModal({
        title: '支付失败',
        content: message,
        confirmText: '重新支付',
        cancelText: '稍后支付',
        success: (res) => {
          if (res.confirm) {
            // 重新支付
            setTimeout(() => {
              this.payOrder()
            }, 500)
          }
        }
      })
    }
  },

  // 联系配送员
  contactDelivery() {
    wx.showModal({
      title: '联系配送员',
      content: '配送员电话：186****1234\n正在为您配送，请耐心等待',
      showCancel: false
    })
  },

  // 确认收货
  confirmOrder() {
    wx.showModal({
      title: '确认收货',
      content: '确认已收到商品吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '确认收货成功',
            icon: 'success'
          })
          
          // 更新订单状态
          this.setData({
            'order.status': 'COMPLETED',
            'order.completedAt': new Date()
          })
        }
      }
    })
  },

  // 评价订单
  reviewOrder() {
    const order = this.data.order
    wx.navigateTo({
      url: `/pages/review/review?orderId=${order.id}&storeId=${order.store.id}`
    })
  },

  // 再来一单
  reorder() {
    const order = this.data.order
    
    // 将订单商品添加到购物车
    order.items.forEach(item => {
      const product = {
        id: item.productId,
        name: item.name,
        price: item.price,
        imageUrl: item.image,
        specifications: item.specifications
      }
      
      for (let i = 0; i < item.quantity; i++) {
        app.addToCart(product, order.store.id)
      }
    })
    
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    })
    
    // 跳转到店铺详情
    setTimeout(() => {
      wx.navigateTo({
        url: `/pages/store-detail/store-detail?id=${order.store.id}&orderType=delivery`
      })
    }, 1500)
  },

  // 联系商家
  contactStore() {
    const order = this.data.order
    
    // 使用safeGet安全获取商家信息
    const storeName = safeGet(order, 'store.name', '商家')
    const storePhone = safeGet(order, 'store.phone', '暂无电话信息')
    const storeAddress = safeGet(order, 'store.address', '')
    
    // 如果连基本的store对象都没有，显示异常
    if (!safeGet(order, 'store.id')) {
      wx.showToast({
        title: '商家信息异常',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '联系商家',
      content: `${storeName}\n电话：${storePhone}`,
      showCancel: storePhone !== '暂无电话信息',
      cancelText: '取消',
      confirmText: storePhone !== '暂无电话信息' ? '拨打电话' : '知道了',
      success: (res) => {
        if (res.confirm && storePhone !== '暂无电话信息') {
          // 尝试拨打电话
          wx.makePhoneCall({
            phoneNumber: storePhone,
            fail: (error) => {
              console.error('拨打电话失败:', error)
              wx.showToast({
                title: '拨打失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  // 获取订单详情
  fetchOrderDetail() {
    const orderId = this.data.orderId
    
    request.get(`/orders/${orderId}`, {}, {
      // 模拟订单详情数据
      mock: this.getMockOrderDetail(orderId)
    }).then(res => {
      if (res.code === 200 && res.data) {
        // 处理订单数据
        const order = this.formatOrderData(res.data)
        
        this.setData({
          order,
          loading: false
        })
      } else {
        wx.showToast({
          title: res.message || '获取订单详情失败',
          icon: 'none'
        })
      }
      
      // 停止下拉刷新动画
      wx.stopPullDownRefresh()
    }).catch(err => {
      console.error('获取订单详情失败:', err)
      
      this.setData({
        loading: false
      })
      
      // 停止下拉刷新动画
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 格式化订单数据
   */
  formatOrderData(order) {
    if (!order) return null
    
    // 获取状态信息
    const statusInfo = this.data.statusMap[order.status] || {
      text: '未知状态',
      color: '#9e9e9e',
      desc: ''
    }
    
    // 格式化时间
    const createdAt = order.createdAt ? dateUtil.formatDateTime(new Date(order.createdAt)) : ''
    const paidAt = order.paidAt ? dateUtil.formatDateTime(new Date(order.paidAt)) : ''
    const completedAt = order.completedAt ? dateUtil.formatDateTime(new Date(order.completedAt)) : ''
    
    // 计算商品总数
    const totalItems = order.orderItems.reduce((total, item) => total + item.quantity, 0)
    
    return {
      ...order,
      statusText: statusInfo.text,
      statusColor: statusInfo.color,
      statusDesc: statusInfo.desc,
      formattedCreatedTime: createdAt,
      formattedPaidTime: paidAt,
      formattedCompletedTime: completedAt,
      formattedTotalAmount: order.totalAmount.toFixed(2),
      formattedProductAmount: order.productAmount.toFixed(2),
      formattedDeliveryFee: order.deliveryFee.toFixed(2),
      formattedDiscountAmount: order.discountAmount.toFixed(2),
      totalItems
    }
  },

  /**
   * 打开取消订单确认框
   */
  openCancelDialog() {
    this.setData({
      showCancelDialog: true
    })
  },

  /**
   * 关闭取消订单确认框
   */
  closeCancelDialog() {
    this.setData({
      showCancelDialog: false
    })
  },

  /**
   * 打开退款原因选择框
   */
  openRefundDialog() {
    this.setData({
      showRefundDialog: true,
      selectedRefundReason: this.data.refundReasons[0]
    })
  },

  /**
   * 关闭退款原因选择框
   */
  closeRefundDialog() {
    this.setData({
      showRefundDialog: false
    })
  },

  /**
   * 选择退款原因
   */
  selectRefundReason(e) {
    this.setData({
      selectedRefundReason: e.currentTarget.dataset.reason
    })
  },

  /**
   * 申请退款
   */
  requestRefund() {
    const orderId = this.data.orderId
    const reason = this.data.selectedRefundReason
    const amount = this.data.order.totalAmount
    
    payment.refundPayment(orderId, amount, reason)
      .then(result => {
        if (result.success) {
          // 刷新订单详情
          this.fetchOrderDetail()
          
          // 提示成功
          wx.showToast({
            title: '退款申请已提交',
            icon: 'success'
          })
        } else {
          // 退款失败
          wx.showToast({
            title: result.message || '申请退款失败',
            icon: 'none'
          })
        }
        
        // 关闭确认框
        this.closeRefundDialog()
      })
      .catch(err => {
        console.error('申请退款失败:', err)
        
        wx.showToast({
          title: '申请退款失败',
          icon: 'none'
        })
        
        // 关闭确认框
        this.closeRefundDialog()
      })
  },

  /**
   * 查看配送信息
   */
  viewDeliveryInfo() {
    const orderId = this.data.orderId
    
    // 获取配送信息
    request.get(`/orders/${orderId}/delivery`, {}, {
      // 模拟配送信息
      mock: {
        deliveryStatus: 'DELIVERING',
        deliveryNo: 'DEL' + Date.now(),
        deliveryCompany: '蜂鸟配送',
        deliveryMan: {
          name: '张师傅',
          phone: '13812345678'
        },
        currentLocation: {
          latitude: 39.9087,
          longitude: 116.3975,
          address: '北京市朝阳区建国路89号'
        },
        estimatedArrivalTime: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
        deliveryTimeline: [
          { time: new Date(Date.now() - 10 * 60 * 1000).toISOString(), status: '商家已接单', desc: '商家已接受您的订单' },
          { time: new Date(Date.now() - 8 * 60 * 1000).toISOString(), status: '商家已备餐', desc: '商家已完成备餐' },
          { time: new Date(Date.now() - 5 * 60 * 1000).toISOString(), status: '骑手已取餐', desc: '骑手已从商家取餐' },
          { time: new Date(Date.now() - 2 * 60 * 1000).toISOString(), status: '骑手配送中', desc: '骑手正在配送中' }
        ]
      }
    }).then(res => {
      if (res.code === 200 && res.data) {
        // 处理配送信息
        const deliveryInfo = this.formatDeliveryInfo(res.data)
        
        this.setData({
          deliveryInfo,
          showDeliveryInfo: true
        })
      } else {
        wx.showToast({
          title: res.message || '获取配送信息失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('获取配送信息失败:', err)
      
      wx.showToast({
        title: '获取配送信息失败',
        icon: 'none'
      })
    })
  },

  /**
   * 关闭配送信息
   */
  closeDeliveryInfo() {
    this.setData({
      showDeliveryInfo: false
    })
  },

  /**
   * 格式化配送信息
   */
  formatDeliveryInfo(info) {
    if (!info) return null
    
    // 格式化时间
    const estimatedArrivalTime = info.estimatedArrivalTime ? 
      dateUtil.formatTime(new Date(info.estimatedArrivalTime), false) : ''
    
    // 格式化配送时间线
    const deliveryTimeline = info.deliveryTimeline.map(item => {
      return {
        ...item,
        formattedTime: item.time ? dateUtil.formatTime(new Date(item.time), false) : ''
      }
    })
    
    return {
      ...info,
      estimatedArrivalTime,
      deliveryTimeline
    }
  },

  /**
   * 拨打电话
   */
  makeCall(e) {
    const phone = e.currentTarget.dataset.phone
    
    if (!phone) return
    
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },

  /**
   * 复制文本
   */
  copyText(e) {
    const text = e.currentTarget.dataset.text
    
    if (!text) return
    
    wx.setClipboardData({
      data: text,
      success() {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        })
      }
    })
  },

  /**
   * 模拟订单详情数据
   */
  getMockOrderDetail(orderId) {
    return {
      id: parseInt(orderId),
      orderNo: 'ORD20230601001',
      status: 'PENDING_PAYMENT',
      totalAmount: 55.50,
      productAmount: 48.50,
      deliveryFee: 7.00,
      discountAmount: 0.00,
      createdAt: '2023-08-15T14:30:00',
      paidAt: null,
      completedAt: null,
      storeName: '美味餐厅',
      storePhone: '010-12345678',
      storeAddress: '北京市朝阳区建国路89号',
      userName: '张三',
      userPhone: '13812345678',
      userAddress: '北京市朝阳区光华路甲8号院中海广场C1座2102室',
      deliveryType: 'EXPRESS',
      paymentMethod: null,
      paymentTransactionId: null,
      orderItems: [
        { productId: 101, name: '黄焖鸡米饭', price: 22.00, quantity: 1, subtotal: 22.00 },
        { productId: 102, name: '可乐', price: 6.50, quantity: 1, subtotal: 6.50 },
        { productId: 103, name: '炸鸡腿', price: 10.00, quantity: 2, subtotal: 20.00 }
      ],
      remark: '不要辣'
    }
  }
})